<!--
+----------------------------------------------------------------------
| 友得云客  - 开启房产营销新纪元
+----------------------------------------------------------------------
| Copyright (c) 2019~2023 优得（西安）信息科技有限公司版权所有
+----------------------------------------------------------------------
| Licensed 友得云客不是自由软件 未经允许不可移除相关版权
+----------------------------------------------------------------------
| Author: www.youdeyunke.com
+----------------------------------------------------------------------
-->
<template>
    <div class="app-container">
        <ud-card>
            <div style="display: flex;justify-content: space-between;">
                <div>
                </div>
                <div>
                    <el-button style="" type="primary" size="small" icon="el-icon-plus" v-if="btns.create_adminuser"
                        @click="newAdminHandle">添加管理员账号</el-button>
                </div>
            </div>

            <el-divider></el-divider>

            <el-table :data="admins">
                <el-table-column prop="id" label="#" width="80" />
                <el-table-column prop="email" label="用户名" />
                <el-table-column prop="name" label="姓名" />
                <el-table-column prop="mobile" label="手机号" />
                <el-table-column label="角色">
                    <span slot-scope="scope">
                        <span v-for="role in scope.row.roles">
                            <el-tag plain size="mini">{{ role.name }}</el-tag>
                        </span>
                        &nbsp;
                    </span>
                </el-table-column>
                <el-table-column label="有效期">
                    <template slot-scope="scope">
                        <span v-if="scope.row.is_forever">永久</span>
                        <span v-else :style="scope.row.is_expired ? { color: 'red' } : ''">{{ scope.row.expired_at
                            }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="启用">
                    <template slot-scope="scope">
                        <el-switch v-model="scope.row.is_enable" :disabled="loading"
                            @change="updateAdminEnable(scope.row)"></el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="130">
                    <template slot-scope="scope">
                        <el-link v-if="btns.update_adminuser" type="info"
                            @click="editAdminHandle(scope.row)">编辑</el-link>
                        <el-link v-if="btns.update_adminuser_password && !scope.row.is_current" type="success"
                            @click="editAdminPasswordHandle(scope.row)">改密</el-link>
                        <el-link :disabled="scope.row.is_super_admin" v-if="btns.delete_adminuser && !scope.row.is_last && !scope.row.is_super_admin" type="danger"
                            @click="deleteAdminHandle(scope.row.id)">删除</el-link>
                    </template>
                </el-table-column>
            </el-table>
            <el-dialog title="编辑账号" :destroy-on-close="true" :close-on-click-modal="false" :visible.sync="showForm"
                width="400px">
                <admin-user-form :data="currentAdminUser" @change="userChange"></admin-user-form>
            </el-dialog>
            <el-dialog title="修改密码" :destroy-on-close="true" :close-on-click-modal="false"
                :visible.sync="showPasswordForm" width="400px">
                <el-form>
                    <el-form-item label="用户名" v-if="currentAdminUser">
                        <el-input v-model="currentAdminUser.email" :disabled="true" />
                    </el-form-item>
                    <el-form-item label="请输入新密码">
                        <el-input v-model="newpassword" type="password" show-password />
                    </el-form-item>
                    <el-form-item label="确认新密码">
                        <el-input v-model="newpassword2" type="password" show-password />
                    </el-form-item>
                </el-form>
                <div slot="footer">
                    <el-button :loading="loading" size="mini" type="default" @click="cancelPwdHandle"
                        icon="el-icon-close">取消</el-button>
                    <el-button :loading="loading" size="mini" type="primary" @click="submitPwdHandle"
                        icon="el-icon-check">确定</el-button>
                </div>
            </el-dialog>
        </ud-card>
    </div>
</template>

<script>
import { adminUserUpdatePassword, createAdminUser, deleteAdminUser, getAdminUsers, updateAdminUserIsEnable, } from "@/api/adminuser";
import UdCard from '@/components/UdCard';
import AdminUserForm from "./Form";
export default {
    props: {
        btns: { type: Object, default: {} },
    },
    components: { AdminUserForm, UdCard },
    data() {
        return {
            loading: false,
            showForm: false,
            showPasswordForm: false,
            currentAdminUser: null,
            admins: [],
            newpassword: "",
            newpassword2: "",
        };
    },

    watch: {
        showPasswordForm: function (val) {
            if (val) {
                this.newpassword = "";
                this.newpassword2 = "";
            }
        },
    },

    mounted: function () {
        this.loadAdminUsers();
    },

    computed: {},

    methods: {

        isTimeBeforeNow(timeString) {
            // 获取当前时间的时间戳
            const currentTimeStamp = new Date().getTime();

            // 将给定的时间字符串转换为时间戳
            const givenTimeStamp = new Date(timeString).getTime();

            // 比较时间戳，如果给定时间早于当前时间，则返回true，否则返回false
            console.log(givenTimeStamp < currentTimeStamp, timeString);
            return givenTimeStamp < currentTimeStamp;
        },

        updateAdminEnable(adminuser) {
            this.loading = true;
            updateAdminUserIsEnable(adminuser.id).then((resp) => {
                this.loading = false;
                if (resp.code != 0) {
                    return;
                }
                this.$message.success("操作成功");
                this.loadAdminUsers();
            }).finally(() => {
                this.loading = false;
                this.loadAdminUsers();
            });
        },

        newAdminHandle: function () {
            this.currentAdminUser = {
                email: "",
                password: "",
                mobile: "",
                avatar: "",
                role_ids: [],
                name: "",
                expired_at: "",
                is_forever: true,
            };
            this.showForm = true;
        },
        userChange: function () {
            this.loading = true;
            this.showForm = false;
            this.currentAdminUser = null;
            this.loadAdminUsers();
        },
        loadAdminUsers: function () {
            getAdminUsers().then((resp) => {
                this.loading = false;
                this.admins = resp.data.filter((user, i) => {
                    user.role_ids = user.roles.map((r) => {
                        return r.id;
                    });
                    user.is_expired = this.isTimeBeforeNow(user.expired_at)
                    //if (user.email != "admin@udeve.cn") {
                    //  return user;
                    //}
                    return user
                });
            });
        },

        createAdminHandle: function () {
            createAdminUser(this.NewAdminUser).then((resp) => {
                if (resp.status == 0) {
                    this.NewAdminUser["email"] = "";
                    this.loadAdminUsers();
                }
            });
        },

        editAdminHandle: function (user) {
            this.currentAdminUser = user;
            this.showForm = true;
            this.loadAdminUsers();
        },

        editAdminPasswordHandle: function (user) {
            this.currentAdminUser = user;
            this.showPasswordForm = true;
        },

        submitPwdHandle() {
            var data = {
                id: this.currentAdminUser.id,
                password: this.newpassword
            }
            const passwordRegex = /^(?=.{6,20}$)(?!.*\s).*/;
            if (!passwordRegex.test(this.newpassword)) {
                this.$message.error("密码长度在8-20位之间，且不能包含空格");
                return;
            }
            if (this.newpassword != this.newpassword2) {
                this.$message.error("两次密码不一致");
                return;
            }
            this.loading = true;
            adminUserUpdatePassword(data).then((resp) => {
                this.loading = false;
                if (resp.status == 0) {
                    this.$message.success("修改成功");
                    this.showPasswordForm = false;
                    this.newpassword = "";
                    this.currentAdminUser = null;
                    this.loadAdminUsers();
                }
            })
        },

        cancelPwdHandle() {
            this.showPasswordForm = false;
            this.newpassword = "";
            this.currentAdminUser = null;
        },

        deleteAdminHandle: function (aid) {
            this.$confirm("确认要删除这个管理员账号吗？").then(() => {
                deleteAdminUser(aid).then((resp) => {
                    if (resp.status == 0) {
                        this.loadAdminUsers();
                    }
                });
            });
        },
    },
};
</script>

<style scoped></style>
